<template>
  <el-dialog v-model="dialogVisible" title="添加管理员" destroy-on-close width="60%">
    <el-form :model="form" label-width="80px" style="padding: 20px 30px 10px 0">
      <el-form-item prop="avatar" label="头像">
        <el-upload
            action="http://localhost:9999/files/upload"
            :headers="{ token: user.token }"
            :on-success="handleFileSuccess"
            list-type="picture"
        >
          <el-button type="primary">上传头像</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item prop="name" label="用户名">
        <el-input v-model="form.name" autocomplete="off" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item prop="username" label="账号">
        <el-input v-model="form.username" autocomplete="off" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item prop="phone" label="电话">
        <el-input v-model="form.phone" autocomplete="off" placeholder="请输入联系电话"/>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email" autocomplete="off" placeholder="请输入电子邮箱"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref } from 'vue'
import request from "@/utils/request";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  form: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'save'])

const dialogVisible = ref(false)
const user = ref(JSON.parse(localStorage.getItem('code_user') || '{}'))

const handleFileSuccess = (res) => {
  props.form.avatar = res.data
}

const save = () => {
  if (props.form.id) {
    request.put('/user/update', props.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('更新成功')
        localStorage.setItem('code_user', JSON.stringify(props.form))
        emit('save')
        emit('update:modelValue', false)
      } else {
        ElMessage.error(res.msg)
      }
    })
  } else {
    request.post('user/add', props.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('新增成功')
        emit('save')
        emit('update:modelValue', false)
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
}
</script>
